from a115.middleware import ThreadLocals
from django.shortcuts import render_to_response, HttpResponse, get_object_or_404
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.contrib.auth.decorators import login_required, permission_required
from django.core.urlresolvers import reverse
from a115.utils.listutils import compose

__all__ = ["render", "render_to_response", "RequestContext", "login_required", "permission_required", "HttpResponse", "HttpResponseRedirect", "reverse", "get_object_or_404", "logged_in", "redirect_to", "s_", "r_", "form_to_session", "form_view"]

def render(template, context):
    request = ThreadLocals.get_current_request()
    cx = dict(request.session)
    cx.update(context)
    return render_to_response(template, cx, RequestContext(request))
redirect_to = compose(HttpResponseRedirect, reverse)
logged_in = lambda r: r.user.is_authenticated()

def s_(*args):
    # Get or set a session variable
    request = ThreadLocals.get_current_request()
    if len(args) == 1:
        return request.session.get(args[0], None)
    elif len(args) == 2:
        request.session[args[0]]=args[1]
        return args[1]
form_to_session = lambda f, l: [s_(v, f.cleaned_data[v]) for v in l]

def r_(*args):
    # Get a request variable
    request = ThreadLocals.get_current_request()
    return request.REQUEST.get(args[0], None)

def form_view(request, FormClass, context={}, initial={}, saver=None):
    if request.method == 'POST':
        form = FormClass(request.POST)
        if form.is_valid():
            if saver:
                saver(form, context)
            else:
                form.save()
            return redirect_to(form._on_success_url)
    else:
        form = FormClass(initial=initial)
    context.update({'form':form})
    return render(form._template_name, context)

